﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.Net;
using System.Windows;
using System.Windows.Controls;
using System.Windows.Controls.Primitives;
using System.Windows.Documents;
using System.Windows.Input;
using System.Windows.Media;
using System.Windows.Media.Animation;
using System.Windows.Shapes;
using PhoneInfo.Converters;

namespace PhoneInfo
{
    public class TabSwitchItem : ContentControl
    {
        public TabSwitchItem()
        {
          this.DefaultStyleKey = typeof(TabSwitchItem);
        }
        #region Propertys
        public static readonly DependencyProperty HeadProperty =
           DependencyProperty.Register("Head", typeof(object), typeof(TabSwitchItem),
                                       new PropertyMetadata("",null));

        /// <summary>
        /// 选中的TabSwitchItem控件
        /// </summary>
        public object Head
        {
            get { return (object)GetValue(HeadProperty); }
            set { SetValue(HeadProperty, value); }
        }
        #endregion
    }
    public class TabSwitch : ItemsControl
    {
        #region Propertys

        public static readonly DependencyProperty SelectedWidthProperty =
            DependencyProperty.Register("SelectedWidth", typeof(double), typeof(TabSwitch),
                                        new PropertyMetadata(90.0, SelectedWidthPropertyChanged));
        /// <summary>
        /// 选中项的宽度
        /// </summary>
        public double SelectedWidth
        {
            get { return (double)GetValue(SelectedWidthProperty); }
            set { SetValue(SelectedWidthProperty, value); }
        }

        public static readonly DependencyProperty SelectedItemProperty =
            DependencyProperty.Register("SelectedItem", typeof(TabSwitchItem), typeof(TabSwitch),
                                        new PropertyMetadata(null));

        /// <summary>
        /// 选中的TabSwitchItem控件
        /// </summary>
        public TabSwitchItem SelectedItem
        {
            get { return (TabSwitchItem)GetValue(SelectedItemProperty); }
            private set { SetValue(SelectedItemProperty, value); }
        }

        public static readonly DependencyProperty SelectedValueProperty =
            DependencyProperty.Register("SelectedValue", typeof(object), typeof(TabSwitch),
                                        new PropertyMetadata(null));

        /// <summary>
        /// 选中项的内容值
        /// </summary>
        public object SelectedValue
        {
            get { return GetValue(SelectedValueProperty); }
            private set { SetValue(SelectedValueProperty, value); }
        }

        public static readonly DependencyProperty SelectedIndexProperty =
            DependencyProperty.Register("SelectedIndex", typeof(int), typeof(TabSwitch),
                                        new PropertyMetadata(0, SelectedIndexPropertyChanged));
        /// <summary>
        /// 选中项的序号
        /// </summary>
        public int SelectedIndex
        {
            get { return (int)GetValue(SelectedIndexProperty); }
            set { SetValue(SelectedIndexProperty, value); }
        }

        public static readonly DependencyProperty SelectedBackgroundProperty =
            DependencyProperty.Register("SelectedBackground", typeof(Brush), typeof(TabSwitch),
                                        new PropertyMetadata(new SolidColorBrush(Color.FromArgb(255,27,161,226)),
                                                             SelectedBackgroundPropertyChanged));
        /// <summary>
        /// 选择项的背景刷子
        /// </summary>
        public Brush SelectedBackground
        {
            get { return (Brush)GetValue(SelectedBackgroundProperty); }
            set { SetValue(SelectedBackgroundProperty, value); }
        }

        private static void SelectedBackgroundPropertyChanged(DependencyObject o, DependencyPropertyChangedEventArgs e)
        {
            var sender = o as TabSwitch;
            if (sender == null || e.NewValue == e.OldValue) return;
            sender.SetSelectedBackground(e.NewValue as Brush);
        }

        private static void SelectedIndexPropertyChanged(DependencyObject o, DependencyPropertyChangedEventArgs e)
        {
            var sender = o as TabSwitch;
            if (sender == null || e.NewValue == e.OldValue) return;

            sender.SetSelectedIndex((int)e.NewValue);
        }

        private static void SelectedWidthPropertyChanged(DependencyObject o, DependencyPropertyChangedEventArgs e)
        {
            var sender = o as TabSwitch;
            if (sender == null || e.NewValue == e.OldValue) return;

            sender.SetSelectedWidth((double)e.NewValue);
        }
        #endregion
        /// <summary>
        /// 背景的方形
        /// </summary>
        private Grid rectangle;
        /// <summary>
        /// 选中事件
        /// </summary>
        public event RoutedEventHandler Selected;
        /// <summary>
        /// 触发选中事件
        /// </summary>
        /// <param name="e"></param>
        private void OnSelected(RoutedEventArgs e)
        {
            RoutedEventHandler handler = Selected;
            if (handler != null) handler(this, e);
        }
        /// <summary>
        /// 改变选中项
        /// </summary>
        /// <param name="index">索引序号</param>
        public void ChangeSelected(int index)
        {
            if (index < 0 || index > Items.Count) return;
            ;
            SelectedIndex = index;
            foreach(TabSwitchItem i in Items)
                i.Foreground = new SolidColorBrush(Common.HtmlToColor("#FF60AFF1"));

            var switchItem = Items[index] as TabSwitchItem;
            if (switchItem != null)
            {
                SelectedItem = switchItem;
                SelectedValue = switchItem.Content;
            }
            else
            {
                SelectedValue = Items[index];
            }
            switchItem.Foreground = new SolidColorBrush(Common.HtmlToColor("#ffffff"));
            OnSelected(new RoutedEventArgs());
        }
        public TabSwitch()
        {
            DefaultStyleKey = typeof(TabSwitch);
        }
        public override void OnApplyTemplate()
        {
            base.OnApplyTemplate();
            rectangle = (Grid)GetTemplateChild("rectangle");
            SetSelectedBackground(SelectedBackground);
            SetSelectedWidth(SelectedWidth);
            SetSelectedIndex(SelectedIndex);
        }
        /// <summary>
        /// 设置选中背景的宽度
        /// </summary>
        /// <param name="itemWidth"></param>
        private void SetSelectedWidth(double itemWidth)
        {
            if (rectangle == null) return;
            rectangle.Width = itemWidth;
        }
        /// <summary>
        /// 设置选中背景的刷子
        /// </summary>
        /// <param name="brush"></param>
        private void SetSelectedBackground(Brush brush)
        {
            if (rectangle == null) return;
        }
        /// <summary>
        /// 设置选中的项目
        /// </summary>
        /// <param name="index">索引序号</param>
        private void SetSelectedIndex(int index)
        {
            if (rectangle == null) return;
            if (index < 0 || index > Items.Count) return;

            double x = SelectedWidth * index;
            var compositeTransform = (CompositeTransform)rectangle.RenderTransform;
            if (Math.Abs(compositeTransform.TranslateX - x) > 1)
                compositeTransform.TranslateX = SelectedWidth * index;
        }

#if SILVERLIGHT
        /// <summary>
        /// 重写鼠标左键放开事件
        /// </summary>
        /// <param name="e"></param>
        protected override void OnMouseLeftButtonUp(MouseButtonEventArgs e)
        {
            Point point = e.GetPosition(this);
            var x = (int)(point.X / SelectedWidth) * SelectedWidth;
            int index = (int)(x / SelectedWidth);
            ShowAnimation(x);
            ChangeSelected(index);

            base.OnMouseLeftButtonUp(e);
        }

#else

        /// <summary>
        /// 重写触摸点中事件
        /// </summary>
        /// <param name="e"></param>
        protected override void OnTap(GestureEventArgs e)
        {
            Point point = e.GetPosition(this);

            var x = (int) (point.X/SelectedWidth)*SelectedWidth;
            int index = (int) (x/SelectedWidth);
            ShowAnimation(x);
            ChangeSelected(index);
            base.OnTap(e);
        }
#endif

        /// <summary>
        /// 选中后的动画
        /// </summary>
        /// <param name="x"></param>
        private void ShowAnimation(double x)
        {
            //移动X坐标，并使用EasingFunction的弹簧特效
            var animation = new DoubleAnimation
            {
                Duration = new Duration(new TimeSpan(0, 0, 0, 0, 500)),
                To = x,
                EasingFunction =
                new ElasticEase { EasingMode = EasingMode.EaseOut, Oscillations = 1, Springiness = 5 }
            };
           // CompositeTransform.TranslateX
            Storyboard.SetTarget(animation, rectangle);
            Storyboard.SetTargetProperty(animation, new PropertyPath("(UIElement.RenderTransform).(CompositeTransform.TranslateX)"));
            var storyboard = new Storyboard();
            storyboard.Children.Add(animation);
            storyboard.Begin();
        }
    }

   
}
